package com.gy.ai.agent.client;

import com.gy.ai.agent.listener.ReqClientListener;
import com.gy.ai.agent.util.SysOkHttpClientUtil;
import com.gy.ai.agent.util.SysUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * @author LGY
 * Create by 2025/6/18 15:42
 */
@Slf4j
public class NdJsonClient implements BaseReqClient, Callback {

    private static final MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");


    private OkHttpClient okHttpClient;
    private ReqClientListener listener;
    private boolean isStop = false;

    @Override
    public void start(String url, Map<String, String> headers, String payload, ReqClientListener listener) {
        this.listener = listener;
        this.isStop = false;
        Request.Builder rBuilder = new Request.Builder()
                .url(url);
        if (headers != null && !headers.isEmpty()) {
            headers.forEach(rBuilder::addHeader);
        }
        RequestBody body = RequestBody.create(payload, JSON_TYPE);
        rBuilder.post(body);
        this.okHttpClient = SysOkHttpClientUtil.buildDefaultClient();
        log.info("消息发送载体: {}", payload);
        this.listener.onStart(this);
        this.okHttpClient.newCall(rBuilder.build()).enqueue(this);
    }

    @Override
    public void stop() {
        tryToStop();
    }


    @Override
    public void onFailure(@NotNull Call call, @NotNull IOException e) {
        try {
            this.listener.onFailure(this, SysUtil.getFailureThrowable(e, null));
        } finally {
            tryToStop();
        }
    }

    @Override
    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
        if (!response.isSuccessful()) {
            tryToStop();
            return;
        }
        ResponseBody body = response.body();
        if (body == null) {
            tryToStop();
            return;
        }
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(body.byteStream()))) {
            String line = reader.readLine();
            while (StringUtils.isNotBlank(line)) {
                try {
                    if (StringUtils.isNotBlank(line) &&
                            line.trim().startsWith("{") &&
                            line.trim().endsWith("}")) {
                        this.listener.onMessage(this, line);
                    } else {
                        this.listener.onMessage(this, "{" + line + "}");
                    }
                } finally {
                    line = reader.readLine();
                }
            }
        } finally {
            tryToStop();
        }
    }


    private boolean tryToStop() {
        if (!this.isStop) {
            try {
                this.isStop = true;
                this.listener.onStop(this);
            } finally {
                if (okHttpClient != null) {
                    okHttpClient.dispatcher().executorService().shutdown();
                }
            }
            return true;
        }
        return false;
    }
}
